// lib/views/group_detail_screen.dart
import 'package:chat/controller/group_detail_controller..dart';
import 'package:chat/model/group_detail_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

final GroupDetailController controller = Get.find();

class GroupDetailScreen extends StatelessWidget {
  const GroupDetailScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(title: const Text('聊天详情'), centerTitle: true, backgroundColor: Colors.white, elevation: 0, foregroundColor: Colors.black),
      body: Obx(() {
        if (controller.groupDetail.value == null) {
          return const Center(child: CircularProgressIndicator());
        }
        final group = controller.groupDetail.value!;
        return SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 群成员部分
              _buildMembersSection(group),
              Container(height: 16, color: Color(0XFFF2F3F7)),
              // 群组信息部分
              _buildGroupInfoSection(group),
              Container(height: 16, color: Color(0XFFF2F3F7)),
              // 功能设置部分
              _buildFunctionSection(group),
              Container(height: 16, color: Color(0XFFF2F3F7)),
              // 解散群组按钮
              _buildDismissButton(),
            ],
          ),
        );
      }),
    );
  }

  Widget _buildMembersSection(GroupDetail group) {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          // 标题行（保持不变）
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Row(
              children: [
                const Text('群成员', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                Text('(${group.members.length})', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                const Spacer(),
                const Icon(Icons.chevron_right, color: Colors.grey),
              ],
            ),
          ),
          // 成员列表 + 操作按钮（关键修改部分）
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10),
            child: LayoutBuilder(
              builder: (context, constraints) {
                // 计算每个项目的宽度（考虑间距）
                final itemWidth = (constraints.maxWidth - (4 * 12)) / 5; // 总宽度减去4个间距后平分5份
                return Wrap(
                  spacing: 12, // 水平间距
                  runSpacing: 12, // 垂直间距
                  children: [
                    // 成员列表（最多显示10个：5x2）
                    ...group.members.take(10).map((member) => SizedBox(width: itemWidth, child: _buildMemberItem(member))),
                    // 操作按钮（确保宽度一致）
                    SizedBox(width: itemWidth, child: _buildActionButton(icon: Icons.add, itemWidth: itemWidth, onPressed: () {})),
                    // 减号按钮
                    if (group.members.isNotEmpty) SizedBox(width: itemWidth, child: _buildActionButton(icon: Icons.remove, itemWidth: itemWidth, onPressed: () {})),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  // 成员项组件
  Widget _buildMemberItem(GroupMember member) {
    return SizedBox(
      //width: 56, // 固定宽度保证对齐
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          CircleAvatar(radius: 30, backgroundImage: AssetImage(member.avatarUrl)),
          const SizedBox(height: 4),
          Text(member.name, style: const TextStyle(fontSize: 12), maxLines: 1, overflow: TextOverflow.ellipsis),
        ],
      ),
    );
  }

  // 操作按钮组件
  Widget _buildActionButton({required IconData icon, required double itemWidth, required VoidCallback onPressed}) {
    return SizedBox(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: itemWidth,
            height: itemWidth,
            decoration: BoxDecoration(color: Colors.grey[200], borderRadius: BorderRadius.circular(30)),
            child: IconButton(icon: Icon(icon, color: Colors.black), onPressed: onPressed),
          ),
        ],
      ),
    );
  }

  Widget _buildGroupInfoSection(GroupDetail group) {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          _buildInfoItem('群组名称', controller.setRemark),
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: Row(
                children: [Expanded(child: Text('群二维码', style: TextStyle(fontSize: 16))), Icon(Icons.qr_code, color: Colors.grey, size: 24), Icon(Icons.chevron_right, color: Colors.grey, size: 24)],
              ),
            ),
          ),
          _buildInfoItem('群公告', controller.setRemark),
          _buildInfoItem('我在本群昵称', controller.setRemark),
          _buildInfoItem('群管理', () {
            Get.toNamed('groupManageScreen');
          }),
        ],
      ),
    );
  }

  Widget _buildFunctionSection(GroupDetail group) {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          _buildSwitchItem('查找聊天记录', onTap: () {}),
          _buildSwitchItem('会话置顶', switchValue: group.isTop, onChanged: (value) => controller.toggleTop()),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Row(
              children: [Expanded(child: Text('定时清理群消息', style: TextStyle(fontSize: 16))), Text('请设置时间', style: TextStyle(fontSize: 16)), Icon(Icons.chevron_right, color: Colors.grey, size: 24)],
            ),
          ),
          Padding(padding: const EdgeInsets.symmetric(horizontal: 16), child: Text('设置定时清理后，系统会定时清理规定时间的群消息，清理后的消息无法恢复，请谨慎设置', style: TextStyle(fontSize: 12, color: Colors.grey[600]))),
        ],
      ),
    );
  }

  Widget _buildInfoItem(String title, VoidCallback onTap) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Row(children: [Expanded(child: Text(title, style: TextStyle(fontSize: 16))), Icon(Icons.chevron_right, color: Colors.grey, size: 24)]),
      ),
    );
  }

  Widget _buildSwitchItem(String title, {bool switchValue = false, ValueChanged<bool>? onChanged, VoidCallback? onTap}) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Row(
          children: [
            // 标题文本
            Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.normal))),
            // 右侧控件
            CupertinoSwitch(
              value: switchValue,
              onChanged: onChanged,
              activeTrackColor: const Color(0xFF377E8E), // 自定义开启状态颜色
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDismissButton() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          _buildInfoItem('清除聊天记录', controller.setRemark),
          InkWell(
            onTap: controller.dismissGroup,
            child: Container(
              width: double.infinity,
              alignment: Alignment.center,
              padding: const EdgeInsets.symmetric(vertical: 10),
              decoration: BoxDecoration(color: Color(0XFFF2F3F7), borderRadius: BorderRadius.circular(20)),
              child: const Text('解散并删除', style: TextStyle(color: Colors.red)),
            ),
          ),
          const SizedBox(height: 80), // 增加底部间距
        ],
      ),
    );
  }
}
